#incoding=utf-8

from pydemo.control.models import Chart
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import loader, Context
from django.conf import settings
from django.contrib.admin.views.decorators import staff_member_required
from django.views.generic.list_detail import object_list
import csv 

def upload(request):    

    file_obj = request.FILES.get('file', None)
    if file_obj:
        import csv
        import StringIO
        buf = StringIO.StringIO(file_obj.read())
        
        try:
            reader = csv.reader(buf)
        except:
            return render_to_response('control/error.html', {'message':'你需要上传一个csv格式的文件'})
        for row in reader:
            objs = Chart.objects.filter(distribution_frame=row[0])
            if not objs:
                obj = Chart(distribution_frame=row[0], seat_port=row[1], switches_port=row[3],
                      switches_model=row[4], person=row[5], ip=row[6], remark=row[7]               
                )
            else:
                 obj = objs[0]
                 obj.seat_port = row[1]   
                 obj.switches_port = row[3]
                 obj.switches_model = row[4]
                 obj.person = row[5]
                 obj.ip = row[6]
                 obj.remark = row[7]
            obj.save()
        return HttpResponseRedirect('/control/') 
    else:
        return render_to_response('control/error.html', {'message':'需要上传一个文件'}) 

@staff_member_required      
def output(request):
    
    if request.user.username != settings.UPLOAD_USER:
        return render_to_response('control/error.html', {'message':'需要登陆'})
    response = HttpResponse(mimetype='application/vnd.ms-excel', content_type='text/html;charset=UTF-8')
    response['Content-Disposition'] = 'attachment; filename=%s' % 'control.xls'
    
    t = loader.get_template('csv.html')
    objs = Chart.objects.all()
    d = []
    for o in objs:
        d.append((o.distribution_frame, o.seat_port, o.switches_port, o.switches_model, o.person, o.ip, o.remark))  
    c = Context({'data':d})
    response.write(t.render(c))   
    return response      
            
def search(request):
    name = request.REQUEST['search']
    if name:
        extra_lookup_kwargs = {'person':name}
        extra_context = {'searchvalue':search}
        return object_list(request, Chart.objects.filter(person=name), paginate_by=5, extra_context=extra_context)
    return HttpResponseRedirect('/control/')           
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
                 